package com.yonyou.ucf.mdf.app.util;

import com.yonyou.iuap.context.InvocationInfoProxy;

import javax.servlet.http.Cookie;

/**
 * 用于转换参数 处理安全问题
 * Created by wanghaichun
 * on 2020/12/8 10:10 上午
 *
 * @author wanghaichun
 */
public class ParamUtils {
    private static final String LOGKEYOBJ = "log.temp.key.obj";

    private ParamUtils() {
    }


    public static Cookie[] escapeForCookieArray(Cookie[] cookies) {
        if (cookies != null && cookies.length > 0) {
            Cookie[] cleancookies = new Cookie[cookies.length];
            for (int i = 0; i < cookies.length; i++) {
                cleancookies[i] = escapeForObject(cookies[i]);
                cleancookies[i].setHttpOnly(true);
                cleancookies[i].setMaxAge(360);
                cleancookies[i].setSecure(true);
            }
            return cleancookies;
        }
        return cookies;
    }


    private static void pushForObject(Object obj) {
        InvocationInfoProxy.setExtendAttribute(LOGKEYOBJ, obj);
    }

    public static <T> T escapeForObject(T obj) {
        pushForObject(obj);
        return (T) popObj();
    }

    public static String cleanSqlInject(String value) {
        return (null == value) ? null : value.replaceAll("(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|"
                + "(\\b(select|update|and|or|delete|insert|truncate|char|into|substr|ascii|declare|exec|count|master|drop|execute)\\b)", "");
    }
    private static Object popObj() {
        return InvocationInfoProxy.getExtendAttribute(LOGKEYOBJ);
    }

}

